﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Collections.Specialized;
using System.ComponentModel;

namespace ObjectModel.Utilities
{
    public class CollectionItemListener<T>
        where T : INotifyCollectionChanged, ICollection
    {
        public event PropertyChangedEventHandler ItemPropertyChanged;

        public CollectionItemListener(T collection)
        {
            collection.CollectionChanged += collection_CollectionChanged;
            RegisterForItemPropertyChangedEvents(collection);
        }

        void RegisterForItemPropertyChangedEvents(IEnumerable collection)
        {
            foreach (var item in collection)
            {
                var observable = item as INotifyPropertyChanged;
                observable.PropertyChanged += item_PropertyChanged;
            }
        }

        void DeregisterFromItemPropertyChangedEvents(IEnumerable collection)
        {
            foreach (var item in collection)
            {
                var observable = item as INotifyPropertyChanged;
                observable.PropertyChanged -= item_PropertyChanged;
            }
        }

        void collection_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            if (e.OldItems != null)
                DeregisterFromItemPropertyChangedEvents(e.OldItems);

            if (e.NewItems != null)
                RegisterForItemPropertyChangedEvents(e.NewItems);
        }

        void item_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            OnItemChanged(sender, e);
        }

        protected void OnItemChanged(object item, PropertyChangedEventArgs e)
        {
            if (ItemPropertyChanged != null)
                ItemPropertyChanged(item, e);
        }
    }
}
